package com.atguigu.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.auth.fengin.MemberFeignService;
import com.atguigu.auth.utils.ConstantWxUtils;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.common.utils.HttpClientUtils;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;

/**
 * @Author ShiJieLin
 * @Date 2022/4/25 10:38
 * @Version 1.0
 */
@Controller
@RequestMapping("/ucenter/wx")
@Slf4j
public class WxApiController {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 生成微信扫描二维码
     *
     * @return
     */
    @GetMapping("/login")
    public String getWxCode() {

        // 微信开放平台授权baseUrl  %s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {
        }

        // 设置%s里面值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
        );
        // 重定向到请求微信地址里面
        return "redirect:" + url;
    }

    @GetMapping("/callback")
    public String callback(String code, String state,
                           HttpSession session) {
        try {
            // 1 获取code值，临时票据，类似于验证码
            // 2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            // 拼接三个参数 ：id  秘钥 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            // 请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
            // 使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            // 远程调用会员服务，注册或者登陆
            R weixinLogin = memberFeignService.weixinLogin(accessTokenInfo);
            // 返回成功
            if (weixinLogin.getCode() == 0) {
                MemberResponseVo data = weixinLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                session.setAttribute("loginUser", data);
                log.info("登录成功：用户信息：{}", data.toString());
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } catch (Exception e) {
            log.info("微信登陆出错!", e);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
